package com.meiyu.live;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.umeng.analytics.MobclickAgent;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.LiveRequest;
import com.meiyu.live.net.MultipartEntity;
import com.meiyu.live.net.MultipartRequest;
import com.meiyu.live.net.ReqPackage;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.MultiPartParam;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.popj.MsgInfo;
import com.meiyu.live.util.ToastUtil;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.List;

public abstract class BaseActivity extends AutoLayoutActivity implements
        Response.ErrorListener {

//    protected NetLoadingDailog dlgLoad;
//
//    private boolean isNeedDlg = true;

    private final DisplayMetrics displayMetrics = new DisplayMetrics();

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//        dlgLoad = new NetLoadingDailog(this);
        BaseApplication.getApp().addTask(this);
        // // 发布时需注释
        // CrashHandler crashHandler = CrashHandler.getInstance();
        // // 传入参数必须为Activity，否则AlertDialog将不显示。
        // crashHandler.init(this);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getApp().removeTask(this);
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
//        dlgLoad.dismissDialog();
        Log.e("response", volleyError.toString());
        if (volleyError instanceof NetworkError) {
            ToastUtil.show("网络异常，请确认网络通畅后重试");
        } else if (volleyError instanceof TimeoutError) {
            ToastUtil.show("请求数据超时");
        } else {
//            ToastUtil.show("服务器异常");
            volleyError.printStackTrace();
        }
        onError();
    }

    public void onError() {
    }

    public <T> void request(BaseBodyParams params, Class<T> response,
                            Response.Listener<? extends BaseResponse> listener) {
        request(Method.POST, params, response, listener, null);
    }

    public <T> void request(BaseBodyParams params, Class<T> response,
                            Response.Listener<? extends BaseResponse> listener, Response.ErrorListener errorListener) {
        request(Method.POST, params, response, listener, errorListener);
    }

    public <T> void request(int method, BaseBodyParams params,
                            Class<T> response,
                            Response.Listener<? extends BaseResponse> listener, Response.ErrorListener errorListener) {
        Response.Listener<T> l = (Response.Listener<T>) listener;
        String paramStr = new ReqPackage(params).packetParam();
        LiveRequest<T> liveRequest = null;

        if (errorListener == null) {
            errorListener = this;
        }

        liveRequest = new LiveRequest<T>(method, Constant.URL
                + params.getUrl(), response, paramStr, l, errorListener);
        Log.i("net-request:" + Constant.URL
                + params.getUrl(), BaseApplication.mGson.toJson(params));
        liveRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        BaseApplication.getApp().addRequest(liveRequest);

    }

    public <T> void multipartRequest(List<MultiPartParam> partParams, int type, BaseBodyParams params,
                                     Class response,
                                     Response.Listener<T> listener) {
        String paramStr = new ReqPackage(params).packetParam();
        MultipartRequest multipartRequest = new MultipartRequest(Constant.URL, response, type, listener, this);

        // 通过MultipartEntity来设置参数
        MultipartEntity multi = multipartRequest.getMultiPartEntity();
        // 文本参数
        multi.addStringPart("hash", paramStr);

        for (MultiPartParam param : partParams) {
            if (param.getFile() != null) {
                multi.addFilePart(param.getName(), param.getFile(), param.getContentType());
            } else {
                multi.addBinaryPart(param.getName(), param.getData(), param.getFileName(), param.getContentType());
            }
        }

        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        BaseApplication.getApp().addRequest(multipartRequest);

    }

    public SharedPreferences getShared() {
        return getSharedPreferences(Constant.APP_SHARED, 0);
    }

    public int getWidth(float scale) {
        if (scale > 1) {
            return displayMetrics.widthPixels;
        }
        return (int) (displayMetrics.widthPixels * scale);
    }

    public int getHeight(float scale) {
        if (scale > 1) {
            return displayMetrics.heightPixels;
        }
        return (int) (displayMetrics.heightPixels * scale);
    }

    public void handleMessage(MsgInfo info) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        BaseApplication.getApp().start();
        MobclickAgent.onResume(this);
    }

    public void startActivity(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    public void startActivity(Class<?> clazz, int requestCode) {
        Intent intent = new Intent(this, clazz);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 控制软盘开启
     *
     * @param view
     */
    public void showSoftInputFromWindow(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }

    /**
     * 控制软盘关闭
     *
     * @param view
     */
    public void hideSoftInputFromWindow(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
        }
    }
}
